package me.zingon.doc.controller;


import me.zingon.doc.exception.ServiceException;
import me.zingon.doc.model.Project;
import me.zingon.doc.model.UserProject;
import me.zingon.doc.service.CatalogService;
import me.zingon.doc.model.Catalog;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import me.zingon.doc.service.UserProjectService;
import me.zingon.doc.vo.CatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
* Created by ZTCGenerator<zingon@aliyun.com> on 2018-5-31.
*/
@RestController
@RequestMapping("/catalog")
public class CatalogController extends BaseController{

    @Autowired
    CatalogService catalogService;

    @Autowired
    UserProjectService userProjectService;

    @GetMapping("/project/{projectId}")
    public Object listById(@PathVariable("projectId")Integer projectId) throws ServiceException {
        List<CatalogVO> result = new ArrayList<>();
        List<Catalog> catalogs = catalogService.listByProjectIdWithUser(projectId,getUser());
        for (Catalog c:catalogs){
            if(c.getParentId().equals(0)){
                CatalogVO cv=new CatalogVO(c);
                catalogService.getChildren(cv,catalogs,new ArrayList<Integer>());
                result.add(cv);
            }
        }
        return result;
    }

    @PostMapping("")
    public Object save(@RequestBody Catalog catalog) throws ServiceException {
        List<UserProject> loginUps=userProjectService
                .list(new UserProject()
                        .setUserId(getUser().getId())
                        .setProjectId(catalog.getProjectId())
                        .setDeleted(false));
        if(loginUps.size() == 0 || loginUps.get(0).getPower().equals("r")){
            throw new ServiceException("user.project.nopower");
        }
        if(catalog.getId() == null || catalog.getId() == 0){
            if(catalog.getIcon() == null){
                catalog.setIcon("el-icon-tickets");
            }
            catalog.setCreateDate(new Date());
            catalog.setUpdateDate(new Date());
            catalogService.insert(catalog.setUrl(UUID.randomUUID().toString()));
        }else {
            catalog.setUpdateDate(new Date());
            catalogService.update(catalog);
        }
        return new CatalogVO(catalogService.getById(catalog.getId()));
    }


    @GetMapping("/del/{projectId}/{catalogId}")
    public Object del(@PathVariable("projectId") Integer projectId,@PathVariable("catalogId") Integer catalogId) throws ServiceException {
        return catalogService.deleteByIdWithUser(catalogId,projectId,getUser());
    }



}
